<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Models\BalanceLog;
use App\Models\CustomerProduct;
use App\Models\CzMobileBlank;
use App\Models\CzOrder;
use App\Models\CzProduct;
use App\Models\CzSpec;
use App\Models\MiniUser;
use App\Models\Payment;
use App\Models\SysUser;
use App\Services\CzOrderService;
use EasyWeChat\Factory;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;


// 小程序相关接口 （严选优充）
class MiniV3Controller extends ApiBaseController
{
    protected $baseUrl;
    protected $appid;
    protected $mch_id;
    protected $secret;
    protected $miniApp;
    protected $payApp;
    protected $paykey;
    protected $pay_type;
    protected $sys_user_id;



    public function __construct(Request $request)
    {
        // 快享通信
        $miniConfig = config("mini")["yxyc"];
        $this->baseUrl = env('APP_URL');

        $this->appid = $miniConfig['appid'];
        $this->secret = $miniConfig['secret'];
        // 支付类型
        $this->pay_type = $miniConfig['pay_type'];
        // 后台用户
        $this->sys_user_id = 25;

        // logger("appid" . $this->appid);
        $mch_id = $miniConfig['mch_id'];

        $this->paykey = $miniConfig['pay_key'];
        $notify_url = $miniConfig['notify_url'];
        parent::__construct($request);

        $this->miniApp = Factory::miniProgram([
            'log' => [
                'level' => 'debug',
                'file' => storage_path('wechat.log'),
            ],
            "response_type" => "array",
            "app_id" => $this->appid,
            "secret" => $this->secret,
        ]);

        $config = [
            'app_id' => $this->appid, //appid为小程序appid
            'mch_id' => $mch_id,
            'key' => $this->paykey,
            'cert_path' => base_path($miniConfig['cert_path']),
            'key_path' =>  base_path($miniConfig['key_path']),
            'notify_url' => $notify_url
        ];
        $this->payApp = Factory::payment($config);
    }
    // 获取小程序短链接
    public function getShortLink(Request $request)
    {
        $res = $this->miniApp->url_link->generate([
            "path" => "/pages/home/home",
        ]);

        return success($res);
    }
    // // 根据手机号查询运营商和价格
    public function getIspBymobile(Request $request)
    {
        $user_id = $this->sys_user_id;
        $params = $request->all();
        $mobile = $params['mobile'] ?? '';
        $face_value = intval($params['face_value'] ?? '100'); //面值
        if (!$mobile) {
            return success();
        }
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        if (strlen($mobile) != 11) {
            return success();
        }
        $mobile_pref = substr($mobile, 0, 7);
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            return error('归属地查询失败,请仔细核对号码！');
        }
        $city_id = 0;
        $province = "";
        $city = "";
        $isp_name = "";
        $city_id = $mobile_info->area_code;
        $isp_name = $mobile_info->isp;
        $province = $mobile_info->province;
        $city = $mobile_info->city;
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '移动/虚拟':
                $isp = 1;
                break;
            case '移动/物联网':
                $isp = 1;
                break;
            case '移动/未知':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '联通/虚拟':
                $isp = 2;
                break;
            case '联通/物联网':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
            case '广电':
                $isp = 3;
                break;
            case '电信/虚拟':
                $isp = 3;
                break;
            case '电信/物联网':
                $isp = 3;
                break;
        }

        $province_id = $area_info->parent_id;
        $user_spec_id = CustomerProduct::filter(
            [
                'user_id' => $user_id,
                'isp' => $isp
            ]
        )->pluck('spec_id');
        $product_id = CzProduct::filter([
            'mobi_province_id' => $province_id,
            'mobi_city_id' => $city_id,
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])->pluck('id');
        $spec_id = CzSpec::where('face_value', $face_value)->where('status', 1)->whereIn('product_id', $product_id)->pluck('id');
        $user_product = CustomerProduct::filter(
            [
                'user_id' => $user_id,
                'isp' => $isp
            ]
        )->with(['channels'])->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->get();
        if (count($user_product->toArray()) == 0) {

            return error('没有分配产品');
        }
        $temp_arr = $user_product->toArray();
        $cur_user_product_id = $temp_arr[0]['id'];
        foreach ($temp_arr as $key => $val) {
            $product_id = $val['product_id'];
            $prodcut = CzProduct::find($product_id);
            if ($prodcut->city_id) {
                // 分市
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分市');
                break;
            } else if ($prodcut->province_id) {
                // 分省
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分省');
                break;
            }
        }
        $user_product = CustomerProduct::find($cur_user_product_id);
        $user_price = $user_product->user_price;
        // CustomerProduct::where('user_id',$user_id)->where([
        //     ""
        // ])
        // $baseUrl = env('APP_URL');
        $face_img = $this->baseUrl . "/storage/slow_100.jpg";
        if ($face_value == 100) {
            $face_img = $this->baseUrl . "/storage/slow_100.jpg";
            // if ($isp == 1) {
            //     $face_img = $this->baseUrl . "/storage/yd_100.jpg";
            // }
            // if ($isp == 2) {
            //     $face_img = $this->baseUrl . "/storage/lt_100.jpg";
            // }
            // if ($isp == 3) {
            //     $face_img = $this->baseUrl . "/storage/dx_100.jpg";
            // }
        }
        if ($face_value == 200) {
            $face_img = $this->baseUrl . "/storage/slow_200.jpg";
            // if ($isp == 1) {
            //     $this->baseUrl . "/storage/yd_200.jpg";
            // }
            // if ($isp == 2) {
            //     $face_img = $this->baseUrl . "/storage/lt_200.jpg";
            // }
            // if ($isp == 3) {
            //     $face_img = $this->baseUrl . "/storage/dx_200.jpg";
            // }
        }

        $mobile_info->price = $user_price;
        $mobile_info->face_img = $face_img;
        return success([
            "data" => $mobile_info
        ]);
    }
    public function getHomeImg(Request $request)
    {
        $img = $this->baseUrl . "/storage/home.jpg";
        return success([
            'data' => $img,
            "is_show" => true
        ]);
    }
    public function testPay()
    {

        $order = CzOrder::find(1);
        $order->order_sn = time();
        $order->openid = "opkSO61vy8Lw5uMHnjGXV9INAaEQ";
        $order->price =  0.01;
        $user = SysUser::find(27);
        $user->pay_type = "tlhsb";
        $payParamsRes = $this->getPayParams($order, $user);
        if ($payParamsRes['code'] == 200) {
            // 第三方支付
            // third_notify_url
            return success(["data" => $payParamsRes['payInfo']]);
        } else {
            return error('下单失败,' . $payParamsRes['msg']);
        }
    }
    public function getProductByMobile(Request $request)
    {
        $user_id = $this->sys_user_id;
        $mobile = request('mobile');
        if (!$mobile) {
            return success();
        }
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        if (strlen($mobile) != 11) {
            return success();
        }
        $mobile_pref = substr($mobile, 0, 7);
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            //2todo 通过其它接口查询
            return error('获取归属地失败,请联系客服！');
        }
        $city_id = $mobile_info->area_code;
        $isp_name = $mobile_info->isp;
        $province = $mobile_info->province;
        $city = $mobile_info->city;
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '移动/虚拟':
                $isp = 1;
                break;
            case '移动/物联网':
                $isp = 1;
                break;
            case '移动/未知':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '联通/虚拟':
                $isp = 2;
                break;
            case '联通/物联网':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
            case '广电':
                $isp = 3;
                break;
            case '电信/虚拟':
                $isp = 3;
                break;
            case '电信/物联网':
                $isp = 3;
                break;
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }
        $province_id = $area_info->parent_id;
        $user = SysUser::find($user_id);
        $user_spec_id = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->pluck('spec_id');
        $product_id = CzProduct::filter([
            'mobi_province_id' => $province_id,
            'mobi_city_id' => $city_id,
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])->pluck('id');
        $spec_id = CzSpec::where('status', 1)->whereIn('product_id', $product_id)->pluck('id');
        $user_product = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->with([
            'spec' => function ($q) {
                $q->select(['face_value', 'id']);
            },
            "product"
        ])->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->select(['id', 'spec_id', 'product_id', 'user_price'])->get();
        if (count($user_product->toArray()) == 0) {
            // logger($mobile . "没有配置产品" . "订单号：" . $user_order_sn);
            // todo默认产品下单
            // continue;
            return error('没有分配产品');
        }
        $temp_arr = $user_product->toArray();
        // 转换格式
        $arr = [

            [
                "hf_type" => "2",
                "title" => "优惠充值",
                "specs" => []
            ],
            [
                "hf_type" => "1",
                "title" => "极速充值",
                "specs" => []
            ],

        ];
        foreach ($temp_arr as $key => $val) {
            // 
            if ($val['product']['hf_type'] == 1) {
                // 快充
                $data = [
                    "id" => $val['id'],
                    "spec" => $val['spec'],
                    "user_price" => $val['user_price'],
                    "spec_id" => $val['spec_id'],
                    "product_id" => $val['product_id'],
                    "hf_type" => $val['product']['hf_type'],
                ];
                array_push($arr[1]['specs'], $data);
            } else {
                // 慢充
                $data = [
                    "id" => $val['id'],
                    "spec" => $val['spec'],
                    "user_price" => $val['user_price'],
                    "spec_id" => $val['spec_id'],
                    "product_id" => $val['product_id'],
                    "hf_type" => $val['product']['hf_type'],

                ];
                array_push($arr[0]['specs'], $data);
            }
        }

        return success(['data' => [
            "product" => $arr,
            "mobile_info" => $mobile_info
        ]]);
    }
    // 获取快充首页默认产品
    public function getProductList2()
    {
        // $user_id = "26";
        // $user = SysUser::find($user_id);
        // $user_spec_id = CustomerProduct::filter(
        //     [
        //         'user_id' => $user_id,
        //         'isp' => $isp
        //     ]
        // )->pluck('spec_id');
        $data = [
            [
                "spec" => [
                    "face_value" => 50,
                ],
                "id" => 1,
                "user_price" => "50.00",
            ],
            [
                "spec" => [
                    "face_value" => 100,
                ],
                "id" => 2,
                "user_price" => "100.00",
            ],
            [
                "spec" => [
                    "face_value" => 200,
                ],
                "id" => 3,
                "user_price" => "200.00",
            ],
            [
                "spec" => [
                    "face_value" => 300,
                ],
                "id" => 4,
                "user_price" => "300.00",
            ],
            [
                "spec" => [
                    "face_value" => 500,
                ],
                "id" => 5,
                "user_price" => "500.00",
            ],
            [
                "spec" => [
                    "face_value" => 1000,
                ],
                "id" => 6,
                "user_price" => "1000.00",
            ],

        ];
        return success([
            'data' => $data,
            "title" => "极速充值"
        ]);
    }
    // 获取首页产品
    public function getProductList()
    {
        // $user_id = "26";
        // $user = SysUser::find($user_id);
        // $user_spec_id = CustomerProduct::filter(
        //     [
        //         'user_id' => $user_id,
        //         'isp' => $isp
        //     ]
        // )->pluck('spec_id');
        $data = [
            [
                "title" => "优惠充值",
                "specs" => [
                    [
                        "spec" => [
                            "face_value" => 50,
                        ],
                        "id" => 7,
                        "hf_type" => 2,
                        "user_price" => "50.00",
                    ],
                    [
                        "spec" => [
                            "face_value" => 100,
                        ],
                        "id" => 8,
                        "hf_type" => 2,
                        "user_price" => "100.00",
                    ],
                    [
                        "spec" => [
                            "face_value" => 200,
                        ],
                        "id" => 9,
                        "hf_type" => 2,
                        "user_price" => "200.00",
                    ],
                    // [
                    //     "spec" => [
                    //         "face_value" => 300,
                    //     ],
                    //     "user_price" => "300.00",
                    // ],
                    // [
                    //     "spec" => [
                    //         "face_value" => 500,
                    //     ],
                    //     "user_price" => "500.00",
                    // ],
                    // [
                    //     "spec" => [
                    //         "face_value" => 1000,
                    //     ],
                    //     "user_price" => "1000.00",
                    // ],
                ]

            ],
            [
                "title" => "极速充值",
                "specs" => [
                    [
                        "spec" => [
                            "face_value" => 50,
                        ],
                        "id" => 1,
                        "hf_type" => 1,
                        "user_price" => "50.00",
                    ],
                    [
                        "spec" => [
                            "face_value" => 100,
                        ],
                        "id" => 2,
                        "hf_type" => 1,
                        "user_price" => "100.00",
                    ],
                    [
                        "spec" => [
                            "face_value" => 200,
                        ],
                        "id" => 3,
                        "hf_type" => 1,
                        "user_price" => "200.00",
                    ],
                    [
                        "spec" => [
                            "face_value" => 300,
                        ],
                        "id" => 4,
                        "hf_type" => 1,
                        "user_price" => "300.00",
                    ],
                    [
                        "spec" => [
                            "face_value" => 500,
                        ],
                        "id" => 5,
                        "hf_type" => 1,
                        "user_price" => "500.00",
                    ],
                    [
                        "spec" => [
                            "face_value" => 1000,
                        ],
                        "hf_type" => 1,
                        "id" => 6,
                        "user_price" => "1000.00",
                    ],
                ]

            ],

        ];
        return success([
            'data' => $data,
            "title" => "优惠充值"
        ]);
    }
    // 获取首页产品
    public function getHomeProduct(Request $request)
    {
        $data = [
            [
                "face_value" => 50,
                // "sale_price" => 48.5
                "sale_price" => 50.5
            ],
            [
                "face_value" => 100,
                // "sale_price" => 96.99
                "sale_price" => 101
            ],
            [
                "face_value" => 200,
                // "sale_price" => 193.98
                "sale_price" => 202

            ]
        ];
        return success(['data' => $data]);
    }
    public function getDetailImg(Request $request)
    {

        return success([
            "data" => $this->baseUrl . "/storage/banner1.jpg",
        ]);
    }
    public function getDescInfo(Request $request)
    {
        $type = $request['type'] ?? 1;  //1慢充2快充
        $isp = $request['isp'] ?? 1;  //1移动2联通3电信

        $face_value = intval($request['face_value'] ?? 100);  //1移动2联通3电信
        if (!is_numeric($face_value)) {
            // return error('面值不正确');
            $face_value = 100;
        }
        if ($isp == 4) {
            $isp = 3;
        }
        // $slow_discount = "0.96"; //慢充折扣
        // 获取慢充折扣
        $user_id = $this->sys_user_id;

        $slow_discount = "0.95";
        $user_id = $params['user_id'] ?? $user_id;
        // var_dump($user_id);
        $user_spec_id = CustomerProduct::filter(
            [
                'user_id' => $user_id,
                'isp' => $isp
            ]
        )->pluck('spec_id');
        $product_id = CzProduct::filter([
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])->pluck('id');
        $spec_id = CzSpec::where('face_value', $face_value)->whereIn('product_id', $product_id)->where('status', 1)->pluck('id');
        $info = CustomerProduct::filter(
            [
                'user_id' => $user_id,
                'isp' => $isp
            ]
        )->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->first();
        // var_dump($face_value);
        // die;
        if (!$info) {
            logger('isp' . $isp . 'face_value' . $face_value);
        }
        $user_price = $info->user_price;
        $face_img = $this->baseUrl . "/storage/yd_100.jpg";
        // $face_img = $this->baseUrl . "/storage/f_100.jpg";
        if ($user_price / 100  > 0.50) {
            // 100面值
            $slow_discount = $user_price / 100;

            if ($isp == 1) {
                $face_img = $this->baseUrl . "/storage/slow_100.jpg";
            }
            if ($isp == 2) {
                $face_img = $this->baseUrl . "/storage/slow_100.jpg";
            }
            if ($isp == 3) {
                $face_img = $this->baseUrl . "/storage/slow_100.jpg";
            }
        }
        if ($user_price / 100  < 0.50) {
            $slow_discount = $user_price / 100 * 2;
            $face_img = $this->baseUrl . "/storage/f_50.jpg";

            if ($isp == 1) {
                $face_img = $this->baseUrl . "/storage/yd_50.jpg";
            }
            if ($isp == 2) {
                $face_img = $this->baseUrl . "/storage/lt_50.jpg";
            }
            if ($isp == 3) {
                $face_img = $this->baseUrl . "/storage/dx_50.jpg";
            }
        }
        if ($user_price / 100  > 1.50) {
            $slow_discount = $user_price / 100 / 2;
            // $face_img = $this->baseUrl . "/storage/face_value_100.jpg";
            if ($isp == 1) {
                $face_img = $this->baseUrl . "/storage/slow_200.jpg";
            }
            if ($isp == 2) {
                $face_img = $this->baseUrl . "/storage/slow_200.jpg";
            }
            if ($isp == 3) {
                $face_img = $this->baseUrl . "/storage/slow_200.jpg";
            }
        }



        $fast_dicount = "0.998"; //快充折扣
        //    <p style="font-size: 12px;margin-top:7px">【售后时间】09:00~22:00（每天）</p>
        //    <p style="font-size: 12px;margin-top:7px">【客服电话】0769-2288 8969</p>
        // 
        // <span style="color:#f00;">充值类型为慢充</span>
        $rich = '<p style="color:#858585;">温馨提示：</p>
        <div style="font-size: 12px;margin-top:5px;color:#858585;">
            <p style="font-size: 12px;margin-top:5px">1.携号转网号码、副卡号码或运营商黑名单号码（长期欠费或非实名认证）无法完成充值，请勿下单。</p>
            <p style="font-size: 12px;margin-top:5px">2.下单前请核对号码及对应运营商，下单后充值的订单无法撤销，充值成功后订单不支持退款。</p>
            <p style="font-size: 12px;margin-top:5px">3.72小时内到账，急用勿充，到账有时会分批到账。</p>
            <p style="font-size: 12px;margin-top:5px">4.本平台暂不提供开票服务，发票一般由运营商提供。你可以到当地营业厅打印发票，或登录网上营业厅下载电子发票，具体政策请咨询对应的运营商客。</p>
        </div>';

        return success([
            "data" => [
                "title" => "【充值过程中请勿再通过其他渠道下单】",
                "tip" => "订单售后周期为订单完成后30天，超时不予处理",
                "rich" => $rich,
                "contact" => "人工客服：4001588569（09:00-22:00）",
                "slow_discount" => $slow_discount,
                "fast_discount" => $slow_discount,
                // "fast_discount" => $fast_dicount,
                "face_img" => $face_img,
                "user_price" => $user_price

            ]
        ]);
    }
    public function getQuestion(Request $request)
    {
        $data = [
            [
                "title" => "多久到账?",
                "con" => "
                    <p>一般会在72小时内到账，月初月末缴费高峰期可能会出现延迟到账的情况，还请您谅解!若订单缴费失败，系统会自动退款，请您放心!
                    </p>
                "
            ],
            [
                "title" => "怎样查询是否到账？",
                "con" => "
                    <p>1.用号码拨打运营商客服电话: 移动10086/联通10010/电信10000，转人工服务，要求查询手机号码缴费记录。</p>
                    <p>2.用号码登录运营商手机营业厅，查询订单完成时间的缴费记录。</p>
                    <p>3.通过以上任一种方式查询到缴费记录说明订单缴费成功话费到账。如果查询不到缴费记录，请联系在线客服处理。
                    </p>
                    "
            ],
            [
                "title" => "成功后未收到短信怎么办？",
                "con" => "
                    <p>1.请点击本小程序的“我的订单”页面，先核实你的订单状态是否[充值成功] 及你充值的号码是否无误;</p>
                    <p>2.若以上核实无误后还未收到到账短信通知，可能是欠费停机无法收到短信，运营商偶尔也会有漏发短信的情况，建议你登录手机营业厅或拨打运营商电话，按提示音查询余额及缴费记录;</p>
                    <p>3.若以上问题均排除仍未到账，请将你的充值订单截图及充值号码发送至[在线客服]，客服将进一步为您核实。
                    </p>
                    "
            ],
            [
                "title" => "为什么充值金额不对?",
                "con" => "
                    <p>手机欠费或者是运营商分次充值，如果手机欠费，运营商会将欠费额度抵消之后剩余部分加到账户余额，运营商分批次到账可稍等待，也可以拨打运营商电话查询。
                    </p>
                    "
            ],
            [
                "title" => "充错号码怎么办?",
                "con" => "
                    <p>亲，非常抱歉!您一付款成功，系统就即时发起充值，人工无法拦截，会马上入账，资金也是即时支付给运营商，运营商不支持冲正交易。所以我们和运营商 (移动、联通、电信) 无法给您办理退款，建议尽快联系充错号码机主自行协商。
                    </p>
                    "
            ],
            [
                "title" => "订单充值失败何时退款?",
                "con" => "
                    <p>若充值失败，系统会自动为您办理全额退款。退款方式如下:
                    </p>
                    <p>
                    1.微信钱包支付的，实时退款到微信钱包，可在[微信支付] 服务通知中查询到;
                    </p>
                    <p>
                    2.银行储蓄卡或信用卡支付的，1-5个工作日原路退款到支付的银行卡。退回的银行卡可能不会发送入账通知的短信，请及时留意银行卡进出账单，以便核实退款到账情况。
                    </p>
                    "
            ],
            [
                "title" => "成功后是否可以开具发票?",
                "con" => "
                    <p>本平台暂不提供开票服务，发票一般由运营商提供。你可以到当地营业厅打印发票，或登录网上营业厅下载电子发票，具体政策请咨询对应的运营商。
                    </p>
                    "
            ],
        ];
        return success(['data' => [
            "list" => $data,
            "mobile" => "客服热线: 4001588569",
            "time" => "工作时间：周一至周五9:00-12:00，13:00-18:00(法定节假日休息)",
            "compony" => "",
        ]]);
    }
    public function getLink()
    {
        $res = config('mini');
        dd($res);
        // $res = $this->miniApp->url_link->generate([
        //     "path" => "pages/record/record",
        //     "query" => ""
        // ]);

        // return success(['data' => $res["url_link"]]);
    }
    public function orderNorifyUrl(Request $request)
    {
        $order_id = request("order_id");
        $pwd = request("pwd");
        $type = request("type");
        if (!$order_id || !$pwd || !$type) {
            return error("fail");
        }
        if ($pwd != "258963") {
            return error("fail");
        }
        $info = CzOrder::find($order_id);
        if (!$info) {
            return error("fail");
        }
        if (!$info->pay_status) {
            return error("fail");
        }
        if ($type == "fail") {
            // 失败通知
            // $data = [
            //     'template_id' => 'muHtejppxS9R914WjN2fCfdiyn7NRe5wgLFNOA7vCXA', // 所需下发的订阅模板id
            //     'touser' => $info->openid,     // 接收者（用户）的 openid
            //     'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            //     'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
            //         'phone_number1' => [
            //             'value' => $info->mobile,
            //         ],
            //         'amount2' => [
            //             'value' => $info->face_value,
            //         ],
            //         'character_string4' => [
            //             'value' => $info->order_sn,
            //         ],


            //     ],
            // ];
            $data = [
                'template_id' => 'ZJV-yjdQKC7QKD_xfW2LE8o7UtmwbDbVU6jJpRHoJ04', // 所需下发的订阅模板id
                'touser' => $info->openid,     // 接收者（用户）的 openid
                'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                    'character_string4' => [
                        'value' => $info->order_sn,
                    ],
                    'phone_number1' => [
                        'value' => $info->mobile,
                    ],
                    'amount2' => [
                        'value' => $info->face_value,
                    ],
                    'thing5' => [
                        'value' => "非常抱歉,订单充值失败!",
                    ],


                ],
            ];
        }
        if ($type == "success") {
            // 成功通知
            // $data = [
            //     'template_id' => 'l0jH7nttsE9tr53PJb8hAyk5FEj2Ub9cSuyBAy1RrfI', // 所需下发的订阅模板id
            //     'touser' => $info->openid,     // 接收者（用户）的 openid
            //     'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            //     'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
            //         'phone_number5' => [
            //             'value' => $info->mobile,
            //         ],
            //         'character_string4' => [
            //             'value' => $info->order_sn,
            //         ],

            //         'amount1' => [
            //             'value' => $info->face_value,
            //         ],
            //         'time3' => [
            //             'value' => date('Y-m-d H:i:s', strtotime($info->updated_at)),
            //         ],
            //     ],
            // ];
            $data = [
                'template_id' => 'Jd0ke1RjhRJtw-on3rGHt4mukRCW3NgmyzxNmvf-pwc', // 所需下发的订阅模板id
                'touser' => $info->openid,     // 接收者（用户）的 openid
                'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                    'character_string6' => [
                        'value' => $info->order_sn,
                    ],
                    'phone_number5' => [
                        'value' => $info->mobile,
                    ],
                    'amount1' => [
                        'value' => $info->face_value,
                    ],
                    'time3' => [
                        'value' => date('Y-m-d H:i:s', strtotime($info->updated_at)),
                    ],
                    'thing7' => [
                        'value' => "订单已充值成功！",
                    ],


                ],
            ];
        }
        $res = $this->miniApp->subscribe_message->send($data);
        logger($info->order_sn . "mini msg send success" . json_encode($res));
        return success($res);
    }
    public function getUserSession(Request $request)
    {
        $user_id  = $this->sys_user_id;
        $code = request('code');
        if (!$code) {
            return error('失败');
        }
        $res = $this->miniApp->auth->session($code);
        // 入库
        $user = MiniUser::updateOrCreate(["openid" => $res['openid']], [
            "session_key" => $res['session_key'],
            "create_by" => $user_id,
            "update_by" => $user_id,
            "appid" => $this->appid

        ]);

        // 返回token
        $token = auth('mini_user')->login($user);

        return success([
            "data" => ['token' => $token, 'expires_in' => auth("mini_user")->factory()->getTTL() * 60]
        ], "登录成功");
    }
    // protected function getPayParamsV2($order, $user, $payInfo)
    // {
    //     $pay_id = $payInfo->id;

    //     $channel_info = Payment::find($pay_id);
    //     $setting_arr = $channel_info->setting;
    //     $setting = [];
    //     // logger(json_encode($setting_arr));
    //     // [{"name":"appid","label":"appid","placeholder":"\u8bf7\u8f93\u5165appid(\u652f\u4ed8\u5e73\u53f0\u7684appid)","val":"00299488"},{"name":"cusid","label":"\u5546\u6237\u53f7","placeholder":"\u8bf7\u8f93\u5165\u5546\u6237\u53f7(\u652f\u4ed8\u5e73\u53f0\u7684\u5546\u6237\u53f7)","val":"660588048161YJT"},{"name":"privateKey","label":"\u79c1\u94a5","placeholder":"\u8bf7\u8f93\u5165\u79c1\u94a5","val":"MIIEpAIBAAKCAQEAsAO8QahoWXaVv1r6wxbB94GIzB2klnFsm3JTv3LRGffRaHYRYSLCRuA52Xo6aKZvKWBra+HB0xftAXm0CjaMS13IiRfzefnC+5AXXCwlE2hCMO\/5g3itk6xNjxzUsNuNhA7puOzn+xboam5uFtSiBdqwZhBftn1X8lqp4Gnf7CVBA80CTWgniCSxqDgZY47\/Y1ejMw0\/wmof5J8yQVBafuBmvwm+WMz9rOkxLqoB7TkEuK5DDXQ3Qan2GG1CQRe1Qi3mfOSTFTDQQaCWHHr+hQQTFVPENVmbX9bxPb1K+OCpWU9gmgnpPI29pDgd1ms37WdfQM2J0sdXvllMeqIfTwIDAQABAoIBAAK3zAxngVUAU8ekrAKfM1eTFH2yZ3w7PCYaWdi2+SuhfAZU7GfHlaBqjfohvQ0opMbKyl3cGpYb5HkFXBZcSUZQqGwVhpj3ll80FmhB9kCad4sx6XRyRJvnKTtwgohIm6LSaCGG5v4lmGksU17e4bGdcuPglNnIjbccV0sz11VaJ1yKwTcbq7ZRCYBXZ\/UECzzCJRF+\/Ohuww1PWFd07ElRs4kM448dOYPu6yj8uJGZyDMZNhQ3rQXfGCJg8PrV4o1arTQXBslwl3YACNvI8IZU0ACSgxi+53zHKzIkvZGQsRqQ5WL+HnnvAzpGbkpYugIWGa4WE44D2PpHFGpDk0ECgYEA1aKVjlIE4zv4J3mwOT9CJxTqY8gkwV4tGHeQ7zamQ\/CHVhLFdFOTmbel7HgIf5Gudg28rvW+6GQYxcyyNcU3cE54qYiAjFIuYBzODtsYV8jlRO\/Ls7WPSL565T0QxD8N9fHww0fbxN0iv1JbdIDxYCyrMMjhDqEp9r7w23S45ucCgYEA0utOSAA5ETOzKbTg1\/Cx93iTPHkPWRlxxqYgDrpoYeDRQpHZ49Ju3BOCO6FpdqPM4m3gFDyz+4ByU1aWyL7yIbq7rJIurpy3VS4OhEP3UOlQzs7jNyM0gkSbzO99CrIrEbG9vbqG0GANm9gE\/iIer5Qvl6eK7YK27h7C09hhP1kCgYEAgntXFSILUi7illnAxHZalTw1HNS1flVi\/bqpjzG1w3E5d9znNPGHCTAd65w0tJXqFLi3MbVu8MmSR92KS0U1YybKk+GHgiz\/njx5rqEq8RMG1WAQ7qZJ6YhNz43Im9RXVox7HQratBbMjkZjDXlj8\/XUaWuH6kONOePNgHx+IqkCgYASdqjGosZcHCN97iiUnqxllneFHq\/aQ+Dy284InAbRMqX+5telGuG7gDWxVKLv0Mz5sVahTuMOjCL16qmObzCxBTCynaVagbuGyF5a87wtqA77256GUB2jna\/p07kle41LojyS5EYy7YWjc9iUCpaXFijIZNFDk2LCG41AkDuLGQKBgQCzN4NZzhtx5hTDkYvryCWCHqlyeejbVH88BcK7qye+ygpS2YLcwvXZ5w8ImAXtdebmg\/PWVRUIIB2YqD\/xxGukUpn9taqB35ag3pemJJl2AF6m8B\/dazwzEqzc2MpCMmuSFZQ\/Iythio6SAAZM1JwdGKJWhDeCIWTPYMk9acgq+w=="},{"name":"privateKey","label":"\u516c\u94a5","placeholder":"\u8bf7\u8f93\u5165\u516c\u94a5","val":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCm9OV6zH5DYH\/ZnAVYHscEELdCNfNTHGuBv1nYYEY9FrOzE0\/4kLl9f7Y9dkWHlc2ocDwbrFSm0Vqz0q2rJPxXUYBCQl5yW3jzuKSXif7q1yOwkFVtJXvuhf5WRy+1X5FOFoMvS7538No0RpnLzmNi3ktmiqmhpcY\/1pmt20FHQQIDAQAB"},{"name":"sign_type","label":"\u7b7e\u540d\u65b9\u5f0f","placeholder":null,"val":"RSA"}]  
    //     foreach ($setting_arr as $key => $v) {
    //         $setting[$v['name']] = $v['val'];
    //     }
    //     // logger(json_encode($setting));
    //     // logger($setting['privateKey']);
    //     $setting['channel_code'] = $channel_info->payment_code;
    //     $setting['channel_id'] = $pay_id;
    //     $setting['callback_url'] = $channel_info->callback_url;
    //     $temp_file = $channel_info->file_path ?? $channel_info->channel_code;
    //     $channel_file = base_path("payChannel/" . $temp_file . ".php");
    //     logger('order_sn:' . $order->order_sn . ',channel_file:' . $channel_file);
    //     include_once $channel_file;
    //     $obj = new $channel_info['payment_code']($setting);

    //     $submitData = [
    //         'OutTradeNo' => $order->order_sn,
    //         'Body' => $order->product_name ?? '充值支付',
    //         'TotalAmount' => $order->price * 100,
    //         'OpenId' => $order->openid,
    //         'SubAppId' => $this->appid,
    //         "success_back_page" => ""
    //     ];

    //     $res = $obj->submitOrder($submitData);
    //     $data = [
    //         "code" => 200,
    //         "msg" => "",
    //         "payInfo" => []
    //     ];
    //     if ($res['status'] == 1) {
    //         $data['payInfo'] = $res['payInfo'];
    //         $data['msg'] = "获取成功";
    //     } else {
    //         $data['code'] = 500;
    //         $data['msg'] = $res['msg'] ?? '支付参数获取失败';
    //     }
    //     return $data;
    // }
    // 获取支付参数
    protected function getPayParams($order, $user)
    {
        // $order = CzOrder::find(4887);
        // dd(date('Y-m-d H:i:s', strtotime($order->updated_at)));

        // if (env('third_type') == 1) {
        if ($user->pay_type == "jinfu") {
            $channel_file = base_path("payChannel/jinfu/" . "jinfu.php");
            $callback_url = env("third_notify_url") . "/jinfu";
            $account = env('third_account');
            $third_key = env('third_key');
            include_once $channel_file;
        }
        // if (env('third_type') == 2) {
        if ($user->pay_type == "jinfu2") {
            $channel_file = base_path("payChannel/jinfu/" . "jinfu.php");
            $callback_url = env("third_notify_url") . "/jinfu2";
            $account = env('third_account2');
            $third_key = env('third_key2');
            include_once $channel_file;
        }
        if ($user->pay_type == "tlhsb_yc") {
            $channel_file = base_path("payChannel/tlhsb/" . "tlhsb.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/tlhsb_yc";
            $setting = config('pay')['tlhsb_yc'];
            $setting['callback_url'] = $callback_url;
            logger("支付参数" . json_encode($setting));

            $submitData = [
                'OutTradeNo' => $order->order_sn,
                'Body' => $order->product_name ?? '充值支付',
                'TotalAmount' => $order->price * 100,
                'OpenId' => $order->openid,
                'SubAppId' => $this->appid,
                "success_back_page" => ""
            ];
            $payClassName = "tlhsb";
            $obj = new $payClassName($setting);

            $res = $obj->submitOrder($submitData);
            $data = [
                "code" => 200,
                "msg" => "",
                "payInfo" => []
            ];
            if ($res['status'] == 1) {
                $data['payInfo'] = $res['payInfo'];
                $data['msg'] = "获取成功";
            } else {
                $data['code'] = 500;
                $data['msg'] = $res['msg'] ?? '支付参数获取失败';
            }
            return $data;
        }
        if ($user->pay_type == "tlhsb_yc_1YJT") {
            $channel_file = base_path("payChannel/tlhsb/" . "tlhsb.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/tlhsb_yc_1YJT";
            $setting = config('pay')['tlhsb_yc_1YJT'];
            $setting['callback_url'] = $callback_url;
            logger("支付参数" . json_encode($setting));

            $submitData = [
                'OutTradeNo' => $order->order_sn,
                'Body' => $order->product_name ?? '充值支付',
                'TotalAmount' => $order->price * 100,
                'OpenId' => $order->openid,
                'SubAppId' => $this->appid,
                "success_back_page" => ""
            ];
            $payClassName = "tlhsb";
            $obj = new $payClassName($setting);

            $res = $obj->submitOrder($submitData);
            $data = [
                "code" => 200,
                "msg" => "",
                "payInfo" => []
            ];
            if ($res['status'] == 1) {
                $data['payInfo'] = $res['payInfo'];
                $data['msg'] = "获取成功";
            } else {
                $data['code'] = 500;
                $data['msg'] = $res['msg'] ?? '支付参数获取失败';
            }
            return $data;
        }
        if ($user->pay_type == "huilian") {
            $channel_file = base_path("payChannel/huilian/" . "huilian.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huilian";
            // $account = env('third_account3');
            // $third_key = env('third_key3');
            // logger('pay' . json_encode(config('pay')));
            $setting = config('pay')['huilian'];
            $setting['callback_url'] = $callback_url;

            $submitData = [
                'OutTradeNo' => $order->order_sn,
                'Body' => $order->product_name ?? '充值支付',
                'TotalAmount' => $order->price * 100,
                'OpenId' => $order->openid,
                'SubAppId' => $this->appid,
                "success_back_page" => ""
            ];
            $payClassName = "huilian";
            $obj = new $payClassName($setting);

            $res = $obj->submitOrder($submitData);
            $data = [
                "code" => 200,
                "msg" => "",
                "payInfo" => []
            ];
            if ($res['status'] == 1) {
                $data['payInfo'] = $res['payInfo'];
                $data['msg'] = "获取成功";
            } else {
                $data['code'] = 500;
                $data['msg'] = $res['msg'] ?? '支付参数获取失败';
            }
            return $data;
        }
        if ($user->pay_type == "huilian_022") {
            $channel_file = base_path("payChannel/huilian/" . "huilian.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huilian_022";
            // $account = env('third_account3');
            // $third_key = env('third_key3');
            // logger('pay' . json_encode(config('pay')));
            $setting = config('pay')['huilian_022'];
            $setting['callback_url'] = $callback_url;

            $submitData = [
                'OutTradeNo' => $order->order_sn,
                'Body' => $order->product_name ?? '充值支付',
                'TotalAmount' => $order->price * 100,
                'OpenId' => $order->openid,
                'SubAppId' => $this->appid,
                "success_back_page" => ""
            ];
            $payClassName = "huilian";
            $obj = new $payClassName($setting);

            $res = $obj->submitOrder($submitData);
            $data = [
                "code" => 200,
                "msg" => "",
                "payInfo" => []
            ];
            if ($res['status'] == 1) {
                $data['payInfo'] = $res['payInfo'];
                $data['msg'] = "获取成功";
            } else {
                $data['code'] = 500;
                $data['msg'] = $res['msg'] ?? '支付参数获取失败';
            }
            return $data;
        }
        if ($user->pay_type == "huilian_022_si") {
            $channel_file = base_path("payChannel/huilian/" . "huilian.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huilian_022_si";
            // $account = env('third_account3');
            // $third_key = env('third_key3');
            // logger('pay' . json_encode(config('pay')));
            $setting = config('pay')['huilian_022_si'];
            $setting['callback_url'] = $callback_url;

            $submitData = [
                'OutTradeNo' => $order->order_sn,
                'Body' => $order->product_name ?? '充值支付',
                'TotalAmount' => $order->price * 100,
                'OpenId' => $order->openid,
                'SubAppId' => $this->appid,
                "success_back_page" => ""
            ];
            $payClassName = "huilian";
            $obj = new $payClassName($setting);

            $res = $obj->submitOrder($submitData);
            $data = [
                "code" => 200,
                "msg" => "",
                "payInfo" => []
            ];
            if ($res['status'] == 1) {
                $data['payInfo'] = $res['payInfo'];
                $data['msg'] = "获取成功";
            } else {
                $data['code'] = 500;
                $data['msg'] = $res['msg'] ?? '支付参数获取失败';
            }
            return $data;
        }
        if ($user->pay_type == "huilian2") {
            $channel_file = base_path("payChannel/huilian2/" . "huilian2.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huilian2";
            $setting = config('pay')['huilian2'];
            $setting['callback_url'] = $callback_url;

            $submitData = [
                'OutTradeNo' => $order->order_sn,
                'Body' => $order->product_name ?? '充值支付',
                'TotalAmount' => $order->price * 100,
                'OpenId' => $order->openid,
                'SubAppId' => $this->appid,
                "success_back_page" => ""
            ];
            $payClassName = "huilian2";
            $obj = new $payClassName($setting);

            $res = $obj->submitOrder($submitData);
            $data = [
                "code" => 200,
                "msg" => "",
                "payInfo" => []
            ];
            if ($res['status'] == 1) {
                $data['payInfo'] = $res['payInfo'];
                $data['msg'] = "获取成功";
            } else {
                $data['code'] = 500;
                $data['msg'] = $res['msg'] ?? '支付参数获取失败';
            }
            return $data;
        }


        $setting = [
            "account" => $account,
            "key" => $third_key,
            "callback_url" => $callback_url,
        ];
        $payClassName = "jinfu";
        $obj = new $payClassName($setting);
        $order_data = [
            "TotalAmount" => $order->price * 100,
            "OutTradeNo" => $order->order_sn,
            "Body" => $order->product_name,
            "success_back_page" => "",
            "SubAppId" => $this->appid,
            "OpenId" => $order->openid,
        ];
        $res = $obj->submitOrder($order_data);
        $data = [
            "code" => 200,
            "msg" => "",
            "payInfo" => []
        ];

        if ($res['status'] == 1) {
            $data['payInfo'] = $res['payInfo'];
            $data['msg'] = "获取成功";
        } else {
            $data['code'] = 500;
            $data['msg'] = $res['msg'] ?? '支付参数获取失败';
        }
        return $data;
    }
    public function getOrderList(Request $request)
    {
        $params = $request->all();
        $user = auth('mini_user')->user();
        if (!isset($params['mobile'])) {
            // return error('fail');
        }
        $params['openid'] = $user->openid;
        $paginator = CzOrder::filter($params)->where('pay_status', 1)
            ->whereBetween('created_at', [time() - 15 * 24 * 3600, time()])
            ->orderBy("id", 'desc')->select(['id', 'created_at', 'isp', 'hf_type', 'order_sn', "product_name", "price", 'face_value', 'mobile', 'area_name', "order_status", "refund_status", 'product_name'])->paginate($this->pageSize);
        $list =  $paginator->items();
        foreach ($list as $key => &$val) {
            // $val['img'] = "http://ty.hfcz888.net/storage/yd_100.jpg";
            $val['img'] = "http://ty.hfcz888.net/storage/slow_100.jpg";
            if (strstr($val['product_name'], '慢充')) {
                $val->hf_type = 2;
            } else {
                $val->hf_type = 1;
            }
            if ($val->hf_type === 1) {
                $val['product_name'] = "极速充值【0-24小时内到账】";
            } else {
                $val['product_name'] = "优惠福利缴费【0-72小时内到账】";
            }
            // $val['product_name'] = "优惠福利缴费【0-72小时内到账】";
            if ($val['face_value'] == 100) {
                if ($val['hf_type'] == 1) {
                    $val['img'] = "http://ty.hfcz888.net/storage/fast_100.jpg";
                } else {
                    $val['img'] = "http://ty.hfcz888.net/storage/slow_100.jpg";
                }
                // $val['img'] = "http://ty.hfcz888.net/storage/slow_100.jpg";
            }
            if ($val['face_value'] == 200) {
                if ($val['hf_type'] == 1) {
                    $val['img'] = "http://ty.hfcz888.net/storage/fast_200.jpg";
                } else {
                    $val['img'] = "http://ty.hfcz888.net/storage/slow_200.jpg";
                }
                // $val['img'] = "http://ty.hfcz888.net/storage/slow_200.jpg";
            }
            //     if ($val['isp'] == 1) {
            //         if ($val['face_value'] == 100) {
            //             if ($val['hf_type'] == 1) {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/yd_fast_100.jpg";
            //             } else {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/yd_100.jpg";
            //             }
            //         }
            //         if ($val['face_value'] == 200) {
            //             if ($val['hf_type'] == 1) {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/yd_fast_200.jpg";
            //             } else {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/yd_200.jpg";
            //             }
            //         }
            //     }
            //     if ($val['isp'] == 2) {
            //         if ($val['face_value'] == 100) {
            //             if ($val['hf_type'] == 1) {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/lt_fast_100.jpg";
            //             } else {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/lt_100.jpg";
            //             }
            //         }
            //         if ($val['face_value'] == 200) {
            //             if ($val['hf_type'] == 1) {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/lt_fast_200.jpg";
            //             } else {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/lt_200.jpg";
            //             }
            //         }
            //     }
            //     if ($val['isp'] == 3 || $val['isp'] == 4) {
            //         if ($val['face_value'] == 100) {
            //             if ($val['hf_type'] == 1) {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/dx_fast_100.jpg";
            //             } else {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/dx_100.jpg";
            //             }
            //         }
            //         if ($val['face_value'] == 200) {
            //             if ($val['hf_type'] == 1) {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/dx_fast_200.jpg";
            //             } else {
            //                 $val['img'] = "http://ty.hfcz888.net/storage/dx_200.jpg";
            //             }
            //         }
            //     }
        }
        $result = [
            'rows' => $list,
            'total' => $paginator->total(), // 获取结果集中的数据总数
            'last_page' => $paginator->lastPage(),
            'currentPage' => $paginator->currentPage()
        ];
        return success($result);
    }
    public function getUserInfo(Request $request)
    {
        // $user = auth('mini_user')->user();
        // $info = MiniUser::find($user->id);
        // return  success([
        //     "data" => [
        //         'openid' => $info['openid']
        //     ]
        // ]);
        return success();
    }
    public function getGoodsList(Request $request)
    {
        $data = [
            [
                "img" => "http://ty.hfcz888.net/storage/yd_100.jpg",
                "price" => "96.00",
                "title" => "全国移动慢充100元话费",
                "face_value" => 100,
                "isp" => 1
            ],
            [
                "img" => "http://ty.hfcz888.net/storage/yd_200.jpg",
                "price" => "192.00",
                "title" => "全国移动慢充200元话费",
                "face_value" => 200,
                "isp" => 1
            ],
            [
                "img" => "http://ty.hfcz888.net/storage/lt_100.jpg",
                "price" => "96.00",
                "title" => "全国联通慢充100元话费",
                "face_value" => 100,
                "isp" => 2
            ],
            [
                "img" => "http://ty.hfcz888.net/storage/lt_200.jpg",
                "price" => "192.00",
                "title" => "全国联通慢充200元话费",
                "face_value" => 200,
                "isp" => 2
            ],


            [
                "img" => "http://ty.hfcz888.net/storage/dx_100.jpg",
                "price" => "96.00",
                "title" => "全国电信慢充100元话费",
                "face_value" => 100,
                "isp" => 3
            ],
            [
                "img" => "http://ty.hfcz888.net/storage/dx_200.jpg",
                "price" => "192.00",
                "title" => "全国电信慢充200元话费",
                "face_value" => 200,
                "isp" => 3
            ],
        ];
        return success([
            "data" => $data
        ]);
    }
    public function getMiniBanner(Request $request)
    {

        return success([
            "data" => [
                [
                    "img" => $this->baseUrl . "/storage/youhui.png",
                    "link" => ""
                ],
                [
                    "img" => $this->baseUrl . "/storage/xhzw.png",
                    "link" => ""
                ]
            ]
        ]);
    }
    public function getContact()
    {
        return success([
            "data" => env('APP_URL') . "/storage/contact.jpg"
        ]);
    }
    // public function urlCode()
    // {
    //     $str = request('str');
    //     $type = request('type', 1);
    //     if ($type == 1) {
    //         $res = urlencode($str);
    //     } else {
    //         $res = urldecode($str);
    //     }
    //     return success([
    //         "data" => ["str" => $res]
    //     ]);
    // }
    // public function getLoveInfo()
    // {
    //     $res_str = $this->httpRequest("https://api.uomg.com/api/rand.qinghua");
    //     $res = json_decode($res_str, true);
    //     if ($res['code'] == 1) {
    //         return success(['data' => $res['content']]);
    //     } else {
    //         return error('错误');
    //     }
    // }
    public function getAreaByPhone(Request $request)
    {
        $phone =   request('phone');
        if (!is_numeric($phone) || strlen($phone) != 11) {
            return error('手机号码格式有误');
        }
        $mobile_pref = substr($phone, 0, 7);
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            //2todo 通过其它接口查询
            return error('获取归属地失败');
        }
        return success(['data' => $mobile_info]);
    }
    public function getDescImg(Request $request)
    {

        return success([
            "data" => [
                $this->baseUrl . "/storage/tip1.jpg",
                $this->baseUrl . "/storage/tip2.jpg",
            ]
        ]);
    }
    // public function getAddressByIp(Request $request)
    // {
    //     $ip = request('ip');
    //     if (!$ip) {
    //         // return error('参数错误');
    //         $ip = request()->ip();
    //         $res_str = $this->httpRequest("http://opendata.baidu.com/api.php?query=" . $ip . "&co=&resource_id=6006&oe=utf8");
    //         $res = json_decode($res_str, true);
    //         if ($res['status'] == 0) {
    //             return success([
    //                 "data" => [
    //                     'ip' => $ip,
    //                     "address" => $res['data'][0]['location']
    //                 ]
    //             ]);
    //         } else {
    //             return error(['info' => "查询失败"]);
    //         }
    //     } else {
    //         $res_str = $this->httpRequest("http://opendata.baidu.com/api.php?query=" . $ip . "&co=&resource_id=6006&oe=utf8");
    //         $res = json_decode($res_str, true);
    //         if ($res['status'] == 0) {
    //             return success([
    //                 "data" => ['info' => $res['data'][0]['location']]
    //             ]);
    //         } else {
    //             return error(['info' => "查询失败"]);
    //         }
    //     }
    // }
    // 小程序下单
    public function createOrder(Request $request)
    {
        $params = $request->all();
        $mobile = $params['mobile'] ?? '';
        $type = $params['type'] ?? 1; //1慢充2快充
        // $user_id = $params['user_id'] ?? 25;
        $mini_user = auth('mini_user')->user();
        $user_id = $mini_user->create_by;

        $face_value = intval($params['face_value'] ?? '100'); //面值
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        if (!is_numeric($face_value)) {
            return error('面值不正确');
        }
        $mobile_pref = substr($mobile, 0, 7);

        $isp_name = "";
        $city_id = 0;
        $province = "";
        $city = "";
        //获取号码归属地
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            logger("归属地获取失败mobile" . $mobile);
            return error("归属地获取失败,请联系客服人员!");
        }
        $city_id = $mobile_info->area_code;
        $isp_name = $mobile_info->isp;
        $province = $mobile_info->province;
        $city = $mobile_info->city;
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '移动/虚拟':
                $isp = 1;
                break;
            case '移动/物联网':
                $isp = 1;
                break;
            case '移动/未知':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '联通/虚拟':
                $isp = 2;
                break;
            case '联通/物联网':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
            case '广电':
                $isp = 3;
                break;
            case '电信/虚拟':
                $isp = 3;
                break;
            case '电信/物联网':
                $isp = 3;
                break;
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }

        $province_id = $area_info->parent_id;
        // 根据面值和运营商获取客户产品
        //获取用户全部产品
        $user = SysUser::find($user_id);
        // 客户的所有面值
        $user_spec_id = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->pluck('spec_id');
        $product_id = CzProduct::filter([
            'mobi_province_id' => $province_id,
            'mobi_city_id' => $city_id,
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])->pluck('id');
        $spec_id = CzSpec::where('face_value', $face_value)->where('status', 1)->whereIn('product_id', $product_id)->pluck('id');
        // 比较价格
        // 获取客户产品
        $user_product = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->with(['channels'])->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->get();
        if (count($user_product->toArray()) == 0) {
            // logger($mobile . "没有配置产品" . "订单号：" . $user_order_sn);
            // todo默认产品下单
            // continue;
            return error('没有分配产品');
        }
        $temp_arr = $user_product->toArray();

        $cur_user_product_id = $temp_arr[0]['id'];
        foreach ($temp_arr as $key => $val) {
            $product_id = $val['product_id'];
            $prodcut = CzProduct::find($product_id);
            if ($prodcut->city_id) {
                // 分市
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分市');
                break;
            } else if ($prodcut->province_id) {
                // 分省
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分省');
                break;
            }
        }
        $user_product = CustomerProduct::find($cur_user_product_id);
        // 下单
        $user_price = $user_product->user_price;
        $is_loop = $user_product->is_loop;
        $submit_order_count = $user_product->submit_order_count;
        $user_product_timeout = $user_product->timeout ?? 0;
        $product_info = CzProduct::find($user_product->product_id);
        $spec_info = CzSpec::find($user_product->spec_id);
        $order_sn = 'YXYC' . date("YmdH") . sprintf('%04d', $user['id']) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999));
        // $hf_type = 1;
        // if ($type == 1) {
        //     $hf_type = 2;
        // } else {
        //     $hf_type = 1;
        // }
        $order_data = [
            "pay_status" => 0,
            "refund_status" => 0,
            'order_sn' => $order_sn,
            "user_order_sn" => $order_sn,
            'product_name' => $product_info->title,
            'mobile' => $mobile,
            'face_value' => $spec_info->face_value,
            'cost' => $user_price,
            'price' => $user_price,
            'area_name' => $province . '-' . $city,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'order_status' => $spec_info->is_cache == 1 ? 5 : 1, //5是压单
            'isp' => $product_info->isp,
            'biz_type' => $product_info->type,
            'hf_type' => $product_info->hf_type,
            'product_id' => $product_info->id,
            'spec_id' => $spec_info->id,
            'is_loop' => $is_loop,
            'submit_from' => 'mini',
            'is_auto' => $spec_info->is_auto,
            'submit_order_count' => $submit_order_count ?? env('ORDER_RE_SUBMIT_LIMIT'),
            "callback_url" => "",
            "create_by" => $user->id,
            "update_by" => $user->id,
            "openid" => $mini_user->openid,
            "appid" => $mini_user->appid
        ];

        //用户分配产品的超时时间
        if ($user_product_timeout > 0) {
            $order_data['timeout'] = time() + intval($user_product_timeout);
        }
        if (strstr($isp_name, '虚拟') || strstr($isp_name, '物联网')) {
            // 虚拟/物联网-号退
            return error("下单失败,原因:", $isp_name);
        }
        if (strstr($isp_name, '未知')) {
            // 虚拟号退
            return error("下单失败,原因:", $isp_name);
        }
        $model = CzOrder::create($order_data);
        $paytime = time();
        // 下单成功获取支付参数
        $result = $this->payApp->order->unify([
            'body' => $product_info->title,
            'out_trade_no' => $order_sn,
            'total_fee' => $user_price * 100,
            'spbill_create_ip' => env('clientIp'), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => env('notify_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            "openid" => $mini_user->openid
            // 'trade_type' => 'MWEB', // 请对应换成你的支付方式对应的值类型
        ]);
        $data = [];
        if ($result['return_code'] == "SUCCESS" && $result['result_code'] == 'SUCCESS') {
            $nonce_str = $result['nonce_str'];
            $prepay_id = $result['prepay_id'];
            $paySign   = md5("appId={$this->appid}&nonceStr={$nonce_str}&package=prepay_id={$prepay_id}&signType=MD5&timeStamp={$paytime}&key={$this->paykey}");
            // 返回给小程序
            $res              = [];
            $res['nonceStr']  = $nonce_str;
            $res['timeStamp'] = strval($paytime); // 小程序支付的timeStamp参数，必须使用这个 timeStamp，因为已经计算到了paySign中
            $res['package']   = "prepay_id=" . $prepay_id;
            $res['paySign']   = $paySign;
            $res['signType']  = 'MD5';
            return success(["data" => $res]);
        } else {
            return error($result['err_code_des']);
        }
        // $payParamsRes = $this->getPayParams($model);
        // if ($payParamsRes['code'] == 200) {
        //     // 第三方支付
        //     // third_notify_url
        //     return success(["data" => $payParamsRes['payInfo']]);
        // } else {
        //     logger('下单失败,' . $payParamsRes['msg']);
        //     return error('下单失败,' . $payParamsRes['msg']);
        // }
    }
    // 快充下单
    public function createOrderForFast(Request $request)
    {
        // return error('系统紧急维护中，请明天再试～');
        $params = $request->all();
        $mobile = $params['mobile'] ?? '';
        $spec_id  = $params['spec_id'] ?? '';
        if (!$spec_id || !$mobile) {
            return error('请求失败');
        }
        $mini_user = auth('mini_user')->user();
        // var_dump($mini_user);
        $user_id = $mini_user->create_by;
        // 
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        if ($this->validateMobileIsBlank($mobile)) {
            return error('号码' . $mobile . '为黑名单号码');
        }
        $mobile_pref = substr($mobile, 0, 7);

        $isp_name = "";
        $city_id = 0;
        $province = "";
        $city = "";
        //获取号码归属地
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            logger("归属地获取失败mobile" . $mobile);
            return error("归属地获取失败,请联系客服人员!");
        }
        $city_id = $mobile_info->area_code;
        $isp_name = $mobile_info->isp;
        $province = $mobile_info->province;
        $city = $mobile_info->city;
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '移动/虚拟':
                $isp = 1;
                break;
            case '移动/物联网':
                $isp = 1;
                break;
            case '移动/未知':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '联通/虚拟':
                $isp = 2;
                break;
            case '联通/物联网':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
            case '广电':
                $isp = 3;
                break;
            case '电信/虚拟':
                $isp = 3;
                break;
            case '电信/物联网':
                $isp = 3;
                break;
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }
        $mobileCount = CzOrder::where('mobile', $mobile)->where('pay_status', 1)->whereBetween("created_at", [time() - 3600 * 24 * 30, time()])->count();
        if ($mobileCount >= 5) {
            return error('号码下单已上限，请过一段时间再下单，谢谢配合');
        }
        $province_id = $area_info->parent_id;
        // 根据面值和运营商获取客户产品

        $user = SysUser::find($user_id);

        //获取用户对应产品
        $user_product = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->with(['channels'])->where('spec_id', $spec_id)->first();
        if (!$user_product) {
            return error('未分配产品');
        }
        $user_price = $user_product->user_price;
        $is_loop = $user_product->is_loop;
        $submit_order_count = $user_product->submit_order_count;
        $user_product_timeout = $user_product->timeout ?? 0;
        $product_info = CzProduct::find($user_product->product_id);
        $spec_info = CzSpec::find($user_product->spec_id);
        if ($spec_info->face_value == 50 || $spec_info->face_value == 1000 || $spec_info->face_value == 500 || $spec_info->face_value == 300) {
            return error('产品维护中,请选择其他面值下单！谢谢配合！');
        }
        $order_sn = 'YXYC' . date("YmdH") . sprintf('%04d', $user['id']) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999));
        $hf_type = 1; //快充
        $order_data = [
            "pay_status" => 0,
            "refund_status" => 0,
            'order_sn' => $order_sn,
            "user_order_sn" => $order_sn,
            'product_name' => $product_info->title,
            'mobile' => $mobile,
            'face_value' => $spec_info->face_value,
            'cost' => $user_price,
            'price' => $user_price,
            'area_name' => $province . '-' . $city,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'order_status' => $spec_info->is_cache == 1 ? 5 : 1, //5是压单
            'isp' => $product_info->isp,
            'biz_type' => $product_info->type,
            'hf_type' => $hf_type,
            'product_id' => $product_info->id,
            'spec_id' => $spec_info->id,
            'is_loop' => $is_loop,
            'submit_from' => 'mini_v3',
            'is_auto' => $spec_info->is_auto,
            'submit_order_count' => $submit_order_count ?? env('ORDER_RE_SUBMIT_LIMIT'),
            "callback_url" => "",
            "create_by" => $user->id,
            "update_by" => $user->id,
            "openid" => $mini_user->openid,
            "appid" => $mini_user->appid
        ];
        if ($user_product_timeout > 0) {
            $order_data['timeout'] = time() + intval($user_product_timeout);
        }
        if (strstr($isp_name, '虚拟') || strstr($isp_name, '物联网')) {
            // 虚拟/物联网-号退
            return error("下单失败,原因:", $isp_name);
        }
        if (strstr($isp_name, '未知')) {
            // 虚拟号退
            return error("下单失败,原因:", $isp_name);
        }
        $model = CzOrder::create($order_data);
        // 判断支付
        if ($user->pay_type == "wx") {
            $paytime = time();
            // 下单成功获取支付参数
            $result = $this->payApp->order->unify([
                'body' => $product_info->title,
                'out_trade_no' => $order_sn,
                'total_fee' => $user_price * 100,
                'spbill_create_ip' => env('clientIp'), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => env('notify_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                "openid" => $mini_user->openid
                // 'trade_type' => 'MWEB', // 请对应换成你的支付方式对应的值类型
            ]);
            $data = [];
            if ($result['return_code'] == "SUCCESS" && $result['result_code'] == 'SUCCESS') {
                $nonce_str = $result['nonce_str'];
                $prepay_id = $result['prepay_id'];
                $paySign   = md5("appId={$this->appid}&nonceStr={$nonce_str}&package=prepay_id={$prepay_id}&signType=MD5&timeStamp={$paytime}&key={$this->paykey}");
                // 返回给小程序
                $res              = [];
                $res['nonceStr']  = $nonce_str;
                $res['timeStamp'] = strval($paytime); // 小程序支付的timeStamp参数，必须使用这个 timeStamp，因为已经计算到了paySign中
                $res['package']   = "prepay_id=" . $prepay_id;
                $res['paySign']   = $paySign;
                $res['signType']  = 'MD5';
                return success(["data" => $res]);
            } else {
                return error($result['err_code_des']);
            }
        } else {
            $payParamsRes = $this->getPayParams($model, $user);
            if ($payParamsRes['code'] == 200) {
                // 第三方支付
                // third_notify_url
                return success(["data" => $payParamsRes['payInfo']]);
            } else {
                return error('下单失败,' . $payParamsRes['msg']);
            }
        }
        return;
    }
    public function createOrder2(Request $request)
    {
        // return error('系统紧急维护中，请稍后再试～');
        $params = $request->all();
        $mobile = $params['mobile'] ?? '';
        $type = $params['type'] ?? 1; //1慢充2快充
        // $user_id = $params['user_id'] ?? 25;
        $mini_user = auth('mini_user')->user();
        $user_id = $mini_user->create_by;

        $face_value = intval($params['face_value'] ?? '100'); //面值
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        if ($this->validateMobileIsBlank($mobile)) {
            return error('号码' . $mobile . '为黑名单号码');
        }
        if (!is_numeric($face_value)) {
            return error('面值不正确');
        }
        if (!in_array($face_value, [100, 200])) {
            return error('维护中,请选择其他面值下单');
        }
        $mobile_pref = substr($mobile, 0, 7);

        $isp_name = "";
        $city_id = 0;
        $province = "";
        $city = "";
        //获取号码归属地
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            logger("归属地获取失败mobile" . $mobile);
            return error("归属地获取失败,请联系客服人员!");
        }
        $city_id = $mobile_info->area_code;
        $isp_name = $mobile_info->isp;
        $province = $mobile_info->province;
        if ($province == "安徽" && $isp_name == "电信") {
            return error('安徽电信目前维护中,暂无法充值,抱歉!');
        }
        $city = $mobile_info->city;
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '移动/虚拟':
                $isp = 1;
                break;
            case '移动/物联网':
                $isp = 1;
                break;
            case '移动/未知':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '联通/虚拟':
                $isp = 2;
                break;
            case '联通/物联网':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
            case '广电':
                $isp = 3;
                break;
            case '电信/虚拟':
                $isp = 3;
                break;
            case '电信/物联网':
                $isp = 3;
                break;
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }
        $mobileCount = CzOrder::where('mobile', $mobile)->where('pay_status', 1)->whereBetween("created_at", [time() - 3600 * 24 * 30, time()])->count();
        if ($mobileCount >= 5) {
            return error('号码下单已上限，请过一段时间再下单，谢谢配合');
        }
        $province_id = $area_info->parent_id;
        // 根据面值和运营商获取客户产品
        //获取用户全部产品
        $user = SysUser::find($user_id);
        // 客户的所有面值
        $user_spec_id = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->pluck('spec_id');
        $product_id = CzProduct::filter([
            'mobi_province_id' => $province_id,
            'mobi_city_id' => $city_id,
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])->pluck('id');
        $spec_id = CzSpec::where('face_value', $face_value)->where('status', 1)->whereIn('product_id', $product_id)->pluck('id');
        // 比较价格
        // 获取客户产品
        $user_product = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->with(['channels'])->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->get();
        if (count($user_product->toArray()) == 0) {
            // logger($mobile . "没有配置产品" . "订单号：" . $user_order_sn);
            // todo默认产品下单
            // continue;
            return error('没有分配产品');
        }
        $temp_arr = $user_product->toArray();

        $cur_user_product_id = $temp_arr[0]['id'];
        foreach ($temp_arr as $key => $val) {
            $product_id = $val['product_id'];
            $prodcut = CzProduct::find($product_id);
            if ($prodcut->city_id) {
                // 分市
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分市');
                break;
            } else if ($prodcut->province_id) {
                // 分省
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分省');
                break;
            }
        }
        $user_product = CustomerProduct::find($cur_user_product_id);
        // 下单
        $user_price = $user_product->user_price;
        $is_loop = $user_product->is_loop;
        $submit_order_count = $user_product->submit_order_count;
        $user_product_timeout = $user_product->timeout ?? 0;
        $product_info = CzProduct::find($user_product->product_id);
        $spec_info = CzSpec::find($user_product->spec_id);
        $order_sn = 'YXYC' . date("YmdH") . sprintf('%04d', $user['id']) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999));
        // $hf_type = 1;
        // if ($type == 1) {
        //     $hf_type = 2;
        // } else {
        //     $hf_type = 1;
        // }
        // 查询支付配置
        $payInfo = Payment::where([
            "user_id" => $user->id,
            "is_default" => 1
        ])->first();
        if (!$payInfo) {
            return error('未配置支付，请联系客服');
        }
        $order_data = [
            "pay_id" => $payInfo->id,
            "pay_status" => 0,
            "refund_status" => 0,
            'order_sn' => $order_sn,
            "user_order_sn" => $order_sn,
            'product_name' => $product_info->title,
            'mobile' => $mobile,
            'face_value' => $spec_info->face_value,
            'cost' => $user_price,
            'price' => $user_price,
            'area_name' => $province . '-' . $city,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'order_status' => $spec_info->is_cache == 1 ? 5 : 1, //5是压单
            'isp' => $product_info->isp,
            'biz_type' => $product_info->type,
            'hf_type' => $product_info->hf_type,
            'product_id' => $product_info->id,
            'spec_id' => $spec_info->id,
            'is_loop' => $is_loop,
            'submit_from' => 'mini_v3',
            'is_auto' => $spec_info->is_auto,
            'submit_order_count' => $submit_order_count ?? env('ORDER_RE_SUBMIT_LIMIT'),
            "callback_url" => "",
            "create_by" => $user->id,
            "update_by" => $user->id,
            "openid" => $mini_user->openid,
            "appid" => $mini_user->appid
        ];

        //用户分配产品的超时时间
        if ($user_product_timeout > 0) {
            $order_data['timeout'] = time() + intval($user_product_timeout);
        }
        if (strstr($isp_name, '虚拟') || strstr($isp_name, '物联网')) {
            // 虚拟/物联网-号退
            return error("下单失败,原因:" . $isp_name);
        }
        if (strstr($isp_name, '未知')) {
            // 虚拟号退
            return error("下单失败,原因:" . $isp_name);
        }
        $model = CzOrder::create($order_data);
        // 判断支付
        $payParamsRes = $this->getPayParamsV2($model, $user, $payInfo, $this->appid);
        if ($payParamsRes['code'] == 200) {
            // 第三方支付
            // third_notify_url
            return success(["data" => $payParamsRes['payInfo']]);
        } else {
            return error('下单失败,' . $payParamsRes['msg']);
        }

        if ($user->pay_type == "wx") {
            $paytime = time();
            // 下单成功获取支付参数
            $result = $this->payApp->order->unify([
                'body' => $product_info->title,
                'out_trade_no' => $order_sn,
                'total_fee' => $user_price * 100,
                'spbill_create_ip' => env('clientIp'), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => env('notify_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                "openid" => $mini_user->openid
                // 'trade_type' => 'MWEB', // 请对应换成你的支付方式对应的值类型
            ]);
            $data = [];
            if ($result['return_code'] == "SUCCESS" && $result['result_code'] == 'SUCCESS') {
                $nonce_str = $result['nonce_str'];
                $prepay_id = $result['prepay_id'];
                $paySign   = md5("appId={$this->appid}&nonceStr={$nonce_str}&package=prepay_id={$prepay_id}&signType=MD5&timeStamp={$paytime}&key={$this->paykey}");
                // 返回给小程序
                $res              = [];
                $res['nonceStr']  = $nonce_str;
                $res['timeStamp'] = strval($paytime); // 小程序支付的timeStamp参数，必须使用这个 timeStamp，因为已经计算到了paySign中
                $res['package']   = "prepay_id=" . $prepay_id;
                $res['paySign']   = $paySign;
                $res['signType']  = 'MD5';
                return success(["data" => $res]);
            } else {
                return error($result['err_code_des']);
            }
        } else {
            $payParamsRes = $this->getPayParams($model, $user);
            if ($payParamsRes['code'] == 200) {
                // 第三方支付
                // third_notify_url
                return success(["data" => $payParamsRes['payInfo']]);
            } else {
                return error('下单失败,' . $payParamsRes['msg']);
            }
        }
    }
    // 获取产品说明图
    public function getMiniDetailImg(Request $request)
    {
        $isp = request("isp");
        $face_value = request("face_value");
        if (!$isp || !$face_value) {
            return error('失败');
        }
        $img = "http://ty.hfcz888.net/storage/yd_100.jpg";

        if ($isp == 1) {
            if ($face_value == 100) {
                $img = "http://ty.hfcz888.net/storage/yd_100.jpg";
            }
            if ($face_value == 200) {
                $img = "http://ty.hfcz888.net/storage/yd_200.jpg";
            }
        }
        if ($isp == 2) {
            if ($face_value == 100) {
                $img = "http://ty.hfcz888.net/storage/lt_100.jpg";
            }
            if ($face_value == 200) {
                $img = "http://ty.hfcz888.net/storage/lt_200.jpg";
            }
        }
        if ($isp == 3 || $isp == 4) {
            if ($face_value == 100) {
                $img = "http://ty.hfcz888.net/storage/dx_100.jpg";
            }
            if ($face_value == 200) {
                $img = "http://ty.hfcz888.net/storage/dx_200.jpg";
            }
        }
        return success(['data' => $img]);

        // return success([
        //     "data" => $this->baseUrl . "/storage/banner1.jpg",
        // ]);
    }
    public function getOrderInfo()
    {
        $mobile = request("mobile");
        if (!$mobile || strlen($mobile) != 11) {
            return error('请输入正确的手机号!');
        }
        $start_time = time() - 30 * 24 * 60 * 60;
        $end_time = time();
        $list = CzOrder::where('pay_status', 1)->where('mobile', $mobile)->whereBetween('created_at', [$start_time, $end_time])->get()->toArray();

        foreach ($list as $key => &$val) {
            $val['img'] = "http://ty.hfcz888.net/storage/yd_100.jpg";
            if ($val['isp'] == 1) {
                if ($val['face_value'] == 100) {
                    $val['img'] = "http://ty.hfcz888.net/storage/yd_100.jpg";
                }
                if ($val['face_value'] == 200) {
                    $val['img'] = "http://ty.hfcz888.net/storage/yd_200.jpg";
                }
            }
            if ($val['isp'] == 2) {
                if ($val['face_value'] == 100) {
                    $val['img'] = "http://ty.hfcz888.net/storage/lt_100.jpg";
                }
                if ($val['face_value'] == 200) {
                    $val['img'] = "http://ty.hfcz888.net/storage/lt_200.jpg";
                }
            }
            if ($val['isp'] == 3) {
                if ($val['face_value'] == 100) {
                    $val['img'] = "http://ty.hfcz888.net/storage/dx_100.jpg";
                }
                if ($val['face_value'] == 200) {
                    $val['img'] = "http://ty.hfcz888.net/storage/dx_200.jpg";
                }
            }
        }

        return success(['data' => $list]);
    }
    public function validateMobileIsBlank($mobile)
    {
        return  CzMobileBlank::where('mobile', $mobile)->exists();
    }
    public function httpRequest($url, $method = 'GET', $postfields = null, $cookie = '', $refer = '', $headers = array(), $debug = false)
    {
        //header("Content-type:text/html;charset=utf-8");
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        //        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        curl_setopt($ci, CURLOPT_COOKIE, $cookie);/* * *COOKIE带过去** */
        //伪造来源referer
        //        curl_setopt ($ci,CURLOPT_REFERER,'http://sb777.cn:8080/tohersystem/rechargeOrder.do?action=distribution&isDistribution=true');
        curl_setopt($ci, CURLOPT_REFERER, $refer);

        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
    }
}
